package com.qianfeng.plateform2203.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qianfeng.plateform2203.common.constants.RedisConstants;
import com.qianfeng.plateform2203.zuul.feign.CacheService;
import com.qianfeng.plateform2203.zuul.localcache.APIRoutringCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
public class IdempotentsFilter extends ZuulFilter {

    @Autowired
    CacheService cacheService;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 20;
    }

    @Override
    public boolean shouldFilter() {
        final boolean b = RequestContext.getCurrentContext().sendZuulResponse();

        final String method = RequestContext.getCurrentContext().getRequest().getParameter("method");

        String key = RedisConstants.APIRouting_REDIS_PRE+method;

        final Map<Object, Object> map = APIRoutringCache.localcache.get(key);

        String idempotents = null;
        if (map!=null){
            idempotents = (String) map.get("idempotents");
        }

        return b && idempotents!=null && idempotents.equals("1");
    }

    @Override
    public Object run() throws ZuulException {

        final RequestContext currentContext = RequestContext.getCurrentContext();
        final HttpServletRequest request = currentContext.getRequest();
        final String sign = request.getParameter("sign");

        String key = RedisConstants.API_IDEMPOTENTS_PRE+sign;

        // 检查Redis中 该 key 是否存在，如果存在，则属于重复请求 ，拒绝掉
        final String s = cacheService.get(key);

        if (s!=null){
            // 请求有问题，不允许请求继续发给后面的微服务了
            currentContext.setSendZuulResponse(false);

            final HttpServletResponse response = currentContext.getResponse();
            response.setContentType("text/html;charset=utf-8");
            try {
                response.getWriter().println("违反了幂等性要求");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        // 把当前的sign写入 Redis中
        try {
            cacheService.setnx(key,sign,10000);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        cacheService.set(key,sign,100000);

        return null;
    }
}
